﻿#include<filesystem>
#include"./ServerConfig.hpp"
#include"../../Base/Config/CfgDefine.hpp"
#include"../../Base/Config/CfgParseTools.hpp"
#include"../../Third/yaml/include/yaml-cpp/yaml.h"


namespace MMF 
{

    ServerConfig* ServerConfig::sInstance = nullptr;
    std::once_flag ServerConfig::sFlag;
    ServerConfig& ServerConfig::Instance()
    {
        std::call_once(sFlag, []{
            sInstance = new ServerConfig();
            sInstance->Start();
        });

        return *sInstance;
    }


    bool ServerConfig::ParseCfg()
    {
        if (!std::filesystem::exists(SERVER_CFG_FILE))
            return false;
        
        YAML::Node root;
        try 
        {
            //加载配置
            root = YAML::LoadFile(SERVER_CFG_FILE);
            YAML::Node globals = root["Globals"];

            mGlobalCfg.mServerIp = globals["ServerIp"].as<std::string>();
            mGlobalCfg.mCmdServerPort = globals["CommandServerPort"].as<uint16_t>();
            mGlobalCfg.mUnitServerPort = globals["UnitServerPort"].as<uint16_t>();
            mGlobalCfg.mStreamBroadcastPort = globals["StreamBroadcastPort"].as<uint16_t>();
            mGlobalCfg.mStreamBroadcastCount = globals["StreamBroadcastCount"].as<uint16_t>();

            YAML::Node WsCtrl = globals["WsComtrol"];
            mGlobalCfg.mWsCtrlCfg.mRouter = WsCtrl["Router"].as<std::string>();
            mGlobalCfg.mWsCtrlCfg.mPort = WsCtrl["Port"].as<uint16_t>();

            //解析服务的app模块
            YAML::Node Apps = root["Apps"];
            mServerCpt = CfgParseTools::ParseServerComponent(Apps);
            
        }
        catch(...)
        {
            return false;
        }

        mIsLoad = true;
        
        return true;
    }


    bool ServerConfig::Start()
    {
        if (mIsLoad)
            return true;

        return ParseCfg();
    }


    const std::vector<MMFServerCpt>& ServerConfig::ServerApp()
    {
        return mServerCpt;
    }


    const MMFServerCfg& ServerConfig::GlobalCfg()
    {
        return mGlobalCfg;
    }
}